package org.wcf.util.freeMarker;

import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;

import java.io.*;
import java.util.HashMap;
import java.util.Map;

/**
 * @author wuchaofei
 * @date 2016/3/18
 */
public class FreemarkerUtil {
    private static final java.lang.String CONTROLLER_TEMP = "controller.ftl";
    private static final String SERVICE_TEMP = "service.ftl";
    private static final String SERVICE_IMPL_TEMP = "serviceImpl.ftl";
    private static final String BEAN_TEMP = "bean.ftl";
    private static final String RESULTMAP_TEMP = "resultMap.ftl";
    private static final String SIMPLE_MYBATIS_TEMP = "simple_mybatis.ftl";

    public static void main(String[] args) throws IOException, TemplateException {
        /*HashMap<String, Object> data = new HashMap<String, Object>();
        List<String> actions=new ArrayList<String>();

        actions.add("index");
        actions.add("view");

        data.put("actions",actions);
        genController("test", "out/out.ftl", data);*/
    }

    public static void builder(String className,String toFile,Map<String,Object> data,String template) throws IOException, TemplateException{
        //        System.out.println(FreemarkerUtil.class.getResource("/controller.ftl").toExternalForm());
//        System.out.println(FreemarkerUtil.class.getResource("/").toExternalForm());
//        System.out.println(Thread.currentThread().getContextClassLoader().getResource("controller.ftl"));

        String templatePath = FreemarkerUtil.class.getResource("/").getFile();
        File outPutFile = new File(toFile);
        Configuration cfg = new Configuration();
        cfg.setDirectoryForTemplateLoading(new File(templatePath));
        if(data==null){
            data=new HashMap<String, Object>();
        }
        data.put("upperClassName", toUpperCaseFirstOne(className));
        data.put("lowerClassName", toLowerCaseFirstOne(className));

        Template t = cfg.getTemplate(template);
        /*File outPutFile = new File(rootPath + bulidFilePath + fileName
                + ".java");*/
        File outPutDirectory = outPutFile.getParentFile();
        if (!outPutDirectory.exists() || (outPutDirectory.isFile())) {
            outPutDirectory.mkdirs();
        }
        Writer out = new BufferedWriter(new OutputStreamWriter(
                new FileOutputStream(outPutFile), "UTF-8"));
        t.process(data, out);
        out.flush();
        out.close();
    }

    /**
     * 生成控制器
     * @param className
     * @param toFile
     * @param data
     * @throws IOException
     * @throws TemplateException
     */
    public static void genController(String className,String toFile,Map<String,Object> data) {
        try {
            builder(className,toFile,data,CONTROLLER_TEMP);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (TemplateException e) {
            e.printStackTrace();
        }
    }

    /**
     * 生成service
     * @param className
     * @param toFile
     * @param data
     */
    public static void genService(String className,String toFile,Map<String,Object> data) {
        try {
            builder(className,toFile,data,SERVICE_TEMP);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (TemplateException e) {
            e.printStackTrace();
        }
    }

    /**
     * 生成bean
     * @param className
     * @param toFile
     * @param data
     */
    public static void genBean(String className,String toFile,Map<String,Object> data) {
        try {
            builder(className,toFile,data,BEAN_TEMP);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (TemplateException e) {
            e.printStackTrace();
        }
    }

    /**
     * 生成mybatis.xml
     * @param className
     * @param toFile
     * @param data
     */
    public static void resultMapGen(String className, String toFile, Map<String, Object> data) {
        try {
            builder(className,toFile,data, RESULTMAP_TEMP);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (TemplateException e) {
            e.printStackTrace();
        }
    }

    /**
     * 首字母小写
     * @param s
     * @return
     */
    public static String toLowerCaseFirstOne(String s) {
        if (Character.isLowerCase(s.charAt(0)))
            return s;
        else
            return (new StringBuilder())
                    .append(Character.toLowerCase(s.charAt(0)))
                    .append(s.substring(1)).toString();
    }

    /**
     * 首字母大写
     * @param s
     * @return
     */
    public static String toUpperCaseFirstOne(String s) {
        if (Character.isUpperCase(s.charAt(0)))
            return s;
        else
            return (new StringBuilder())
                    .append(Character.toUpperCase(s.charAt(0)))
                    .append(s.substring(1)).toString();
    }

    /**
     * 将字符串按_分割首字母大写，连接起来
     * @param str
     * @return
     */
    public static String splitJoinUpperFirstWord(String str){
        if(str.contains("_")){
            String[] arr = str.split("_");
            StringBuilder sb=new StringBuilder();
            for (int i = 0; i <arr.length; i++) {
                if(i!=0){
                    sb.append(arr[i].substring(0,1).toUpperCase()).append(arr[i].substring(1));
                }else{
                    sb.append(arr[i].substring(0,1).toLowerCase()).append(arr[i].substring(1));
                }
            }
            return sb.toString();
        }
        return str;
    }

    /**
     * 简单生成mybatis xml文件
     * @param className
     * @param toFile
     * @param data
     */
    public static void genSimpleMybatis(String className, String toFile, Map<String, Object> data) {
        try {
            builder(className,toFile,data,SIMPLE_MYBATIS_TEMP);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (TemplateException e) {
            e.printStackTrace();
        }
    }
}
